# coding:utf8
from baike_spider import url_manager, html_downloader, html_parser, html_outputer

# 管理器，下载器，解析器，输出器
# 爬虫调度程序类，描述爬虫调度程序的行为
class SpiderMain(object):

    # 构造函数，初始化各个部分
    def __init__(self):
        self.urls = url_manager.UrlManager()
        self.downloader = html_downloader.HtmlDownloader()
        self.parser = html_parser.HtmlParser()
        self.outputer = html_outputer.HtmlOutput()


    # 运行调度程序
    def craw(self, root_url):
        count = 1
        self.urls.add_new_url(root_url)
        while self.urls.has_new_url():
            try:
                # 取出url
                new_url = self.urls.get_new_url()
                # 根据url下载页内容
                html_content = self.downloader.download(new_url)
                # 将网页内容解析为需要的数据
                new_url, new_data = self.parser.parse(new_url, html_content)
                # 将数据各自存放
                self.urls.add_new_urls(new_url)
                self.outputer.collect_data(new_data)
                if count == 1000:
                    break
                count = count+1
            except Exception as e:
                print '页面失效'
                print e
        # 将数据输出为html文件
        self.outputer.output_html()


# Python中main方法的写法，定义程序入口
if __name__ == "__main__":
    root_url = "https://baike.baidu.com/item/Python/407313"
    spider = SpiderMain()
    spider.craw(root_url)
